package com.cgy.utils.cmd.cmd;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;

import com.cgy.utils.cmd.contants.Systems;
import com.google.common.base.Preconditions;

/**
 * 终端
 * @author CHTK
 */
public class CmdHelper {

    private static final DefaultExecutor DEFAULT_EXECUTOR = new DefaultExecutor();

    /**
     * cmd
     * @param cmd
     * @return
     */
    public static String commandLine(String cmd) {
        return commandLine(cmd, 5 * 1000L);
    }

    /**
     * cmd
     * @param cmd
     * @param timeout
     * @param limit
     * @return
     */
    public static String commandLine(String cmd, long timeout, int limit) {
        Preconditions.checkArgument(limit > 0);

        StringBuilder stringBuilder = new StringBuilder();
        for (int index = 0; index < limit ; index ++ ) {
            stringBuilder.append(commandLine(cmd, timeout));
        }
        return stringBuilder.toString();
    }
    /**
     * cmd
     * @param cmd
     * @param limit
     * @return
     */
    public static String commandLine(String cmd, int limit) {
        return commandLine(cmd, 1 * 1000L, limit);
    }
    /**
     * cmd
     * @param cmd
     * @return
     */
    public static String commandLine(String cmd, long timeout) {

        ExecuteWatchdog executeWatchdog = new ExecuteWatchdog(timeout);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ByteArrayOutputStream errorByteArrayOutputStream = new ByteArrayOutputStream();

        PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(byteArrayOutputStream, errorByteArrayOutputStream);

        CommandLine commandLine = CommandLine.parse(cmd);

        DEFAULT_EXECUTOR.setStreamHandler(pumpStreamHandler);
        DEFAULT_EXECUTOR.setWatchdog(executeWatchdog);
        DEFAULT_EXECUTOR.setExitValues(null);
        try {
            DEFAULT_EXECUTOR.execute(commandLine);
            String code = "UTF-8";
            if(Systems.isWin()) {
                code = "GBK";
            }
            String string = byteArrayOutputStream.toString(code);
            String error = errorByteArrayOutputStream.toString(code);
            System.out.println(string + error);
            return string;
        } catch (IOException e) {
           System.err.println(e.getMessage());
        }
        return null;
    }

}
